package com.gxitsky.utils;

import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.Security;
import java.util.Arrays;
import java.util.Base64;

/**
 * @author gxing
 * @desc 微信加密数据解密工具
 * 微信官网说明：https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html#%E5%8A%A0%E5%AF%86%E6%95%B0%E6%8D%AE%E8%A7%A3%E5%AF%86%E7%AE%97%E6%B3%95
 * @date 2023/7/13
 */
@Slf4j
public class WeChatUtil {
    private static final String KEY_ALGORITHM = "AES";
    private static final String ALGORITHM_STR = "AES/CBC/PKCS7Padding";
    private static Key key;
    private static Cipher cipher;


    /**
     * @param encryptedData 加密的数据
     * @param sessionKey    解密密钥
     * @param iv            解密算法初始向量 iv
     * @return 解密后的字符串
     */
    public static String decryptData(String encryptedData, String sessionKey, String iv) {
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] encryptDataB64 = decoder.decode(encryptedData);
        byte[] sessionKeyB64 = decoder.decode(sessionKey);
        byte[] ivB64 = decoder.decode(iv);
        byte[] bytes = decryptOfDiyIV(encryptDataB64, sessionKeyB64, ivB64);
        String result = new String(bytes, StandardCharsets.UTF_8);
        return result;
    }

    /**
     * 解密方法
     *
     * @param encryptedData 加密的数据
     * @param keyBytes      解密密钥
     * @param ivs           解密算法初始向量 iv
     * @return 解密后的字节数组
     */
    public static byte[] decryptOfDiyIV(byte[] encryptedData, byte[] keyBytes, byte[] ivs) {
        init(keyBytes);
        byte[] encryptedText = null;
        try {
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ivs));
            encryptedText = cipher.doFinal(encryptedData);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encryptedText;
    }

    /**
     * @param keyBytes 解密密钥
     * @desc cipher
     * @author gxing
     * @date 2023/7/13 16:43
     */
    public static void init(byte[] keyBytes) {
        // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
        int base = 16;
        if (keyBytes.length % base != 0) {
            int groups = keyBytes.length / base + (keyBytes.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
            keyBytes = temp;
        }
        // 初始化
        Security.addProvider(new BouncyCastleProvider());
        // 转化成JAVA的密钥格式
        key = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
        try {
            // 初始化cipher
            cipher = Cipher.getInstance(ALGORITHM_STR, "BC");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Test
     * @param args
     */
//    public static void main(String[] args) {
//        String encryptedData = "0WOvynI0cpr3iQ24t98goAH0CCCYZ3ZZh4bYkvmDVaTnNOnLD13fONmRChc2z7/pBrDnnm+pjPDPTCfwuAaBZbuBN+D6xgEmhEOHlE5kjfQZEnwHs4PD/dft4vILUY4A";
//        String iv = "pSxPL6tKKZTUNO7KQGuUcg==";
//        String session_key = "jAHi7QxC49Urbe02I7IsDA==";
//        String s = decryptData(encryptedData, session_key, iv);
//        System.out.println(s);
//        结果: {"mobile":"13423746867","watermark":{"appid":"wx4e32b7b3a3fe23bd","timestamp":1689234444}}
//    }
}

